package com.ffggffgfv.backend.controller;

import com.ffggffgfv.backend.dto.PageResult;
import com.ffggffgfv.backend.dto.RestockDTO;
import com.ffggffgfv.backend.dto.ShelfProductDetailDTO;
import com.ffggffgfv.backend.dto.ShelfQueryDTO;
import com.ffggffgfv.backend.entity.Shelf;
import com.ffggffgfv.backend.service.ShelfProductService;
import com.ffggffgfv.backend.service.ShelfService;
import com.ffggffgfv.backend.util.JWTUtil;
import com.ffggffgfv.backend.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 货架控制器
 */
@RestController
@RequestMapping("/api/shelves")
public class ShelfController {

    @Autowired
    private ShelfService shelfService;

    @Autowired
    private ShelfProductService shelfProductService;

    @Autowired
    private JWTUtil jwtUtil;

    /**
     * 货架列表
     *
     * @param queryDTO 查询条件
     * @param token    JWT令牌
     * @return 货架列表
     */
    @GetMapping
    public Result getShelves(ShelfQueryDTO queryDTO, @RequestHeader(value = "Authorization", required = false) String token) {
        // 如果是普通商家，只能查询自己的货架
        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null) {
                queryDTO.setMerchantId(merchantId);
            }
        }

        PageResult<Shelf> pageResult = shelfService.findByPage(queryDTO);
        return Result.success(pageResult, "共" + pageResult.getTotal() + "条记录");
    }

    /**
     * 根据ID查询货架详情
     *
     * @param id    货架ID
     * @param token JWT令牌
     * @return 货架详情
     */
    @GetMapping("/{id}")
    public Result getShelfById(@PathVariable Long id, @RequestHeader(value = "Authorization", required = false) String token) {
        Shelf shelf = shelfService.findById(id);
        if (shelf == null) {
            return Result.validateFailed("货架不存在");
        }

        // 如果是普通商家，只能查询自己的货架
        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null && !merchantId.equals(shelf.getMerchantId())) {
                return Result.unauthorized("无权查看该货架");
            }
        }

        // 计算货架当前负载
        int currentLoad = shelfService.calculateCurrentLoad(id);

        // 将负载信息添加到返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("shelf", shelf);
        resultMap.put("currentLoad", currentLoad);
        resultMap.put("loadRate", shelf.getCapacity() > 0 ? (double) currentLoad / shelf.getCapacity() * 100 : 0);

        return Result.success(resultMap, "获取货架详情成功");
    }

    /**
     * 查询货架上的商品
     *
     * @param shelfId  货架ID
     * @param pageNum  页码
     * @param pageSize 每页大小
     * @param token    JWT令牌
     * @return 货架商品列表
     */
    @GetMapping("/{shelfId}/products")
    public Result getShelfProducts(
            @PathVariable Long shelfId,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestHeader(value = "Authorization", required = false) String token) {

        Shelf shelf = shelfService.findById(shelfId);
        if (shelf == null) {
            return Result.validateFailed("货架不存在");
        }

        // 如果是普通商家，只能查询自己的货架
        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null && !merchantId.equals(shelf.getMerchantId())) {
                return Result.unauthorized("无权查看该货架商品");
            }
        }

        PageResult<ShelfProductDetailDTO> pageResult = shelfProductService.findByShelfIdWithPage(shelfId, pageNum, pageSize);
        return Result.success(pageResult, "共" + pageResult.getTotal() + "条记录");
    }

    /**
     * 创建货架
     *
     * @param shelf 货架信息
     * @param token JWT令牌
     * @return 创建结果
     */
    @PostMapping
    public Result createShelf(@RequestBody Shelf shelf, @RequestHeader(value = "Authorization") String token) {
        // 从令牌中获取商家ID，验证权限
        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null) {
                // 如果是普通商家，只能创建自己的货架
                if (!isAdminRole(token.substring(7))) {
                    shelf.setMerchantId(merchantId);
                }
            } else {
                return Result.unauthorized("无效的令牌");
            }
        } else {
            return Result.unauthorized("未提供令牌");
        }

        // 参数校验
        if (shelf.getName() == null || shelf.getName().trim().isEmpty()) {
            return Result.validateFailed("货架名称不能为空");
        }
        if (shelf.getLocation() == null || shelf.getLocation().trim().isEmpty()) {
            return Result.validateFailed("货架位置不能为空");
        }
        if (shelf.getMerchantId() == null) {
            return Result.validateFailed("所属商家不能为空");
        }

        Shelf createdShelf = shelfService.create(shelf);
        return Result.success(createdShelf, "货架创建成功");
    }

    /**
     * 更新货架信息
     *
     * @param id    货架ID
     * @param shelf 货架信息
     * @param token JWT令牌
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public Result updateShelf(@PathVariable Long id, @RequestBody Shelf shelf, @RequestHeader(value = "Authorization") String token) {
        Shelf existingShelf = shelfService.findById(id);
        if (existingShelf == null) {
            return Result.validateFailed("货架不存在");
        }

        // 验证权限
        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null) {
                // 如果是普通商家，只能更新自己的货架
                if (!isAdminRole(token.substring(7)) && !merchantId.equals(existingShelf.getMerchantId())) {
                    return Result.unauthorized("无权更新该货架");
                }
            } else {
                return Result.unauthorized("无效的令牌");
            }
        } else {
            return Result.unauthorized("未提供令牌");
        }

        shelf.setId(id);
        Shelf updatedShelf = shelfService.update(id, shelf);
        if (updatedShelf == null) {
            return Result.validateFailed("更新失败");
        }

        return Result.success(updatedShelf, "货架更新成功");
    }

    /**
     * 删除货架
     *
     * @param id    货架ID
     * @param token JWT令牌
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result deleteShelf(@PathVariable Long id, @RequestHeader(value = "Authorization") String token) {
        Shelf existingShelf = shelfService.findById(id);
        if (existingShelf == null) {
            return Result.validateFailed("货架不存在");
        }

        // 验证权限
        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null) {
                // 如果是普通商家，只能删除自己的货架
                if (!isAdminRole(token.substring(7)) && !merchantId.equals(existingShelf.getMerchantId())) {
                    return Result.unauthorized("无权删除该货架");
                }
            } else {
                return Result.unauthorized("无效的令牌");
            }
        } else {
            return Result.unauthorized("未提供令牌");
        }

        boolean result = shelfService.delete(id);
        if (result) {
            return Result.success(null, "货架删除成功");
        } else {
            return Result.validateFailed("删除失败");
        }
    }

    /**
     * 更新货架状态
     *
     * @param id     货架ID
     * @param status 状态
     * @param token  JWT令牌
     * @return 更新结果
     */
    @PutMapping("/{id}/status")
    public Result updateShelfStatus(
            @PathVariable Long id,
            @RequestParam Integer status,
            @RequestHeader(value = "Authorization") String token) {

        Shelf existingShelf = shelfService.findById(id);
        if (existingShelf == null) {
            return Result.validateFailed("货架不存在");
        }

        // 验证权限
        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null) {
                // 如果是普通商家，只能更新自己的货架
                if (!isAdminRole(token.substring(7)) && !merchantId.equals(existingShelf.getMerchantId())) {
                    return Result.unauthorized("无权更新该货架状态");
                }
            } else {
                return Result.unauthorized("无效的令牌");
            }
        } else {
            return Result.unauthorized("未提供令牌");
        }

        // 参数校验
        if (status != 0 && status != 1 && status != 2) {
            return Result.validateFailed("状态值无效");
        }

        Shelf updatedShelf = shelfService.updateStatus(id, status);
        if (updatedShelf == null) {
            return Result.validateFailed("更新失败");
        }

        String statusText;
        switch (status) {
            case 0:
                statusText = "已停用";
                break;
            case 1:
                statusText = "已启用";
                break;
            case 2:
                statusText = "维护中";
                break;
            default:
                statusText = "状态已更新";
        }

        return Result.success(updatedShelf, "货架" + statusText);
    }

    /**
     * 补货操作
     *
     * @param shelfId    货架ID
     * @param restockDTO 补货信息
     * @param token      JWT令牌
     * @return 操作结果
     */
    @PostMapping("/{shelfId}/restock")
    public Result restock(
            @PathVariable Long shelfId,
            @RequestBody RestockDTO restockDTO,
            @RequestHeader(value = "Authorization") String token) {

        Shelf existingShelf = shelfService.findById(shelfId);
        if (existingShelf == null) {
            return Result.validateFailed("货架不存在");
        }

        // 验证权限
        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null) {
                // 如果是普通商家，只能操作自己的货架
                if (!isAdminRole(token.substring(7)) && !merchantId.equals(existingShelf.getMerchantId())) {
                    return Result.unauthorized("无权操作该货架");
                }

                // 设置操作人信息
                if (restockDTO.getOperatorId() == null) {
                    restockDTO.setOperatorId(merchantId);
                }
                if (restockDTO.getOperatorType() == null) {
                    restockDTO.setOperatorType(3); // 假设3代表商家
                }
            } else {
                return Result.unauthorized("无效的令牌");
            }
        } else {
            return Result.unauthorized("未提供令牌");
        }

        // 参数校验
        if (restockDTO.getProductId() == null) {
            return Result.validateFailed("商品ID不能为空");
        }
        if (restockDTO.getQuantity() == null || restockDTO.getQuantity() <= 0) {
            return Result.validateFailed("补货数量必须大于0");
        }

        try {
            ShelfProductDetailDTO result = shelfProductService.restock(shelfId, restockDTO);
            return Result.success(result, "补货成功");
        } catch (Exception e) {
            return Result.failed("补货失败：" + e.getMessage());
        }
    }

    /**
     * 根据RFID标签查询商品信息
     *
     * @param rfidTag RFID标签
     * @return 商品信息
     */
    @GetMapping("/products/rfid/{rfidTag}")
    public Result getProductByRfidTag(@PathVariable String rfidTag) {
        Map<String, Object> result = shelfProductService.findByRfidTag(rfidTag);
        if (result == null) {
            return Result.validateFailed("找不到该RFID标签对应的商品");
        }
        return Result.success(result, "查询成功");
    }

    /**
     * 从货架移除商品
     *
     * @param shelfId   货架ID
     * @param productId 商品ID
     * @param quantity  移除数量
     * @param reason    原因
     * @param rfidTags  RFID标签列表
     * @param token     JWT令牌
     * @return 操作结果
     */
    @DeleteMapping("/{shelfId}/products/{productId}")
    public Result removeProduct(
            @PathVariable Long shelfId,
            @PathVariable Long productId,
            @RequestParam(required = false) Integer quantity,
            @RequestParam(required = false) String reason,
            @RequestBody(required = false) List<String> rfidTags,
            @RequestHeader(value = "Authorization") String token) {

        Shelf existingShelf = shelfService.findById(shelfId);
        if (existingShelf == null) {
            return Result.validateFailed("货架不存在");
        }

        // 验证权限
        Long operatorId = null;
        Integer operatorType = null;

        if (token != null && token.startsWith("Bearer ")) {
            Long merchantId = extractMerchantId(token.substring(7));
            if (merchantId != null) {
                // 如果是普通商家，只能操作自己的货架
                if (!isAdminRole(token.substring(7)) && !merchantId.equals(existingShelf.getMerchantId())) {
                    return Result.unauthorized("无权操作该货架");
                }

                operatorId = merchantId;
                operatorType = isAdminRole(token.substring(7)) ? 2 : 3; // 2-管理员 3-商家
            } else {
                return Result.unauthorized("无效的令牌");
            }
        } else {
            return Result.unauthorized("未提供令牌");
        }

        // 如果未提供原因，设置默认原因
        if (reason == null || reason.trim().isEmpty()) {
            reason = "人工移除";
        }

        try {
            Map<String, Object> result = shelfProductService.removeProduct(
                    shelfId, productId, quantity, reason, rfidTags, operatorId, operatorType);
            return Result.success(result, "商品已从货架移除");
        } catch (Exception e) {
            return Result.failed("移除失败：" + e.getMessage());
        }
    }

    /**
     * 从令牌中提取商家ID
     *
     * @param token JWT令牌
     * @return 商家ID
     */
    private Long extractMerchantId(String token) {
        try {
            // 从令牌中解析商家ID
            // 实际实现应该从JWT令牌中获取用户信息，这里简化实现
            return jwtUtil.extractUserId(token);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断是否为管理员角色
     *
     * @param token JWT令牌
     * @return 是否为管理员
     */
    private boolean isAdminRole(String token) {
        try {
            // 从令牌中解析角色
            // 实际实现应该从JWT令牌中获取用户角色，这里简化实现
            return jwtUtil.hasAdminRole(token);
        } catch (Exception e) {
            return false;
        }
    }
}
